<template>
  <div>
    <el-date-picker
      style="width: 100%"
      @click.native.stop
      @change="changeInfo"
      v-model="val"
      type="daterange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      :picker-options="pickerOptions"
      :default-time="['00:00:00', '23:59:59']"></el-date-picker>
  </div>
</template>

<script>
import { titleCase } from '@/utils/index'
export default {
  name: 'HdDatePicker',
  data() {
    return {
      val: [],
      name: titleCase(this.keyName),
    }
  },
  props: {
    keyName: {
      type: String,
      default: '',
    },
    pickerOptions: {
      type: Object,
      default: () => ({}),
    },
    value: {},
  },
  watch: {
    value: {
      handler(val) {
        console.log(val)
        if (!val || Object.keys(val).length == 0) {
          this.val = []
        } else {
          this.val = [val['begin' + this.name], val['end' + this.name]]
        }
      },
    },
  },
  created() {
    if (!this.value || Object.keys(this.value).length == 0) {
      this.val = []
    } else {
      this.val = [this.value['begin' + this.name], this.value['end' + this.name]]
    }
  },
  mounted() {},
  methods: {
    dispatch(componentName, eventName, params) {
      var parent = this.$parent || this.$root
      var name = parent.$options.componentName

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent

        if (parent) {
          name = parent.$options.componentName
        }
      }
      if (parent) {
        parent.$emit.apply(parent, [eventName].concat(params))
      }
    },
    changeInfo(val) {
      const name = titleCase(this.keyName)
      const tmp = {}
      if (val) {
        tmp['begin' + name] = this.$moment(val[0]).format()
        tmp['end' + name] = this.$moment(val[1]).format()
      } else {
        tmp['begin' + name] = undefined
        tmp['end' + name] = undefined
      }
      this.$emit('input', { ...this.value, ...tmp })
      this.$emit('change', val)
      setTimeout(() => {
        this.dispatch('ElFormItem', 'el.form.change', val)
      })
    },
  },
}
</script>

<style></style>
